package com.vdongchina.thread.Lock;

/**
 * 乐观锁---CAS 比较并替换
 * 乐观锁适用读多写少的情况
 * 自旋算法不能长时间不成功,否则会耗尽cpu资源
 *
 * todo 详细了解线程的生命周期,然后再来
 */
public class CAS {

    public static volatile int race= 0;

    public static void increase(){
        race ++;
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[20];
        for(int i=0;i<20;i++)
        {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    increase();
                }
            });
            threads[i].start();
        }
        while(Thread.activeCount()>1)
        {
            Thread.yield();
        }
        System.out.println(race);

    }




}
